import Vue from 'vue'
import Vuex from 'vuex'
import {Toast} from 'vant'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    goodsNum: 0,// 购物车数量
   
   
  },
  mutations: {
    changeNum(state) {
      state.goodsNum = 0
      if (localStorage.getItem('buycart')) {
        JSON.parse(localStorage.getItem('buycart')).forEach(item => {
          state.goodsNum += item.cartnum
        })
      } else {
        state.goodsNum = 0
      }
    }, 
    //加入购物车方法
    insert(state,arr){
      let buyCartData=[]
      let  isfalse=false
        //判断购物车里是否为空
        
      if(localStorage.getItem('buycart')){
        buyCartData=JSON.parse(localStorage.getItem('buycart'))
        buyCartData.forEach(item=>{
          if(item.id===arr.id){
            item.cartnum++
            isfalse=true
            console.log(5555);
          }
          
        })
        if(!isfalse){
          arr.select=true
            arr.cartnum=1
           buyCartData[buyCartData.length]=arr
          }
          

      }else{
        
        arr.select=true
        arr.cartnum=1
          console.log(buyCartData);
       buyCartData.push(arr)
    
        console.log(arr);
      }
      Toast.success("添加成功")
      localStorage.setItem('buycart' ,JSON.stringify(buyCartData))
      //  changeNum()
      console.log(state);
      //调用方法获取购物车里的数据
      this.commit('changeNum')
    },

  },
  actions: {
   add_cart({commit},item){

    commit('insert',item)
   },
   getNum({commit}){
    commit('changeNum')
  }
  },
  
  modules: {
  }
})
